package cn.lhf.cd.controller;

import javafx.application.Platform;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;

import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;

public abstract class ChildrenController implements Initializable {
    private MainController mainController;

    public void bind(MainController mainController, Object ... args) {
        this.mainController = mainController;
    }

    /**
     * 获取标题
     * @return 标题
     */
    public abstract String getTitle();

    /**
     * 左1按钮
     */
    public void onBtnLeft1() throws Exception {

    }

    /**
     * 左2按钮
     */
    public void onBtnLeft2() throws Exception {

    }

    /**
     * 左3按钮
     */
    public void onBtnLeft3() throws Exception {

    }

    /**
     * 左4按钮
     */
    public void onBtnLeft4() throws Exception {

    }

    /**
     * 右1按钮
     */
    public void onBtnRight1() throws Exception {

    }

    /**
     * 右2按钮
     */
    public void onBtnRight2() throws Exception {

    }

    /**
     * 右3按钮
     */
    public void onBtnRight3() throws Exception {

    }

    /**
     * 右4按钮
     */
    public void onBtnRight4() throws Exception {
    }

    protected MainController getMainController() {
        return mainController;
    }

    private static final Hashtable<Label, Timer> labelTimerHashtable = new Hashtable<>();   //定时任务表

    /**
     * 发送提示
     * @param view 用于显示消息的文本标签
     * @param msg  要显示的消息
     */
    protected static synchronized void sendTip(Label view, String msg) {
        view.setText(msg);
        Timer timer;
        if (labelTimerHashtable.containsKey(view)) {
            timer = labelTimerHashtable.get(view);
            timer.cancel();                         //取消任务
            timer.purge();                          //销毁定时器
            labelTimerHashtable.remove(view);       //从任务表中删除任务
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Platform.runLater(() -> view.setText(null));    //不能直接在子线程中更新UI
                Timer thiz = labelTimerHashtable.get(view);
                thiz.cancel();
                thiz.purge();
                labelTimerHashtable.remove(view);
            }
        }, 15000);                                        //定时15秒
        labelTimerHashtable.put(view, timer);
    }

    /**
     * 清除所有提示
     */
    protected static void clearTips() {
        for (Label view:
                labelTimerHashtable.keySet()) {
            Timer timer = labelTimerHashtable.get(view);
            timer.cancel();
            timer.purge();
            view.setText(null);
        }
        labelTimerHashtable.clear();
    }
}
